package com.ujoku.view.builder;

import com.labillusion.core.platform.web.rest.view.BaseViewBuilder;
import com.ujoku.domain.Favorite;
import com.ujoku.domain.Goods;
import com.ujoku.request.SearchForm;
import com.ujoku.service.CdnService;
import com.ujoku.view.domain.GoodsView;
import com.ujoku.view.domain.Refinement;
import com.ujoku.view.domain.SearchView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
/**
 * Created by Administrator on 2014/10/19.
 */
@Component
public class SearchViewBuilder extends BaseViewBuilder<Goods,GoodsView> {

    @Autowired
    private CdnService cdnService;

    public SearchView builderSearchView(List<Goods> list, Refinement refinement, SearchForm form, List<Favorite> favoriteList) throws Exception {
        SearchView searchView = new SearchView();
        searchView.setList(new ArrayList<>());
        List<Goods> result=BuildPagingResult(list,form);
        if(result!=null && result.size()>0) {
            for (Goods item : result) {
                GoodsView goodsView = Create(item);
                goodsView.setMediumImage(cdnService.buildGoodsImage(item.getGoods_id(), CdnService.Goods_Medium, item.getLast_update().getTime()));
                setGoodsFav(favoriteList,goodsView);
                searchView.getList().add(goodsView);
            }
        }
        searchView.setCount(list.size());
        searchView.setRefinement(refinement);
        return searchView;
    }

    private List<Goods> BuildPagingResult(List<Goods> result,SearchForm form){
        if(CollectionUtils.isEmpty(result)) return null;

        int index=form.getPageIndex();
        int pageSize=form.getPageSize();
        if(index<=0 && pageSize<=0) return result;

        int start= index*pageSize;
        int end=start+pageSize;
        if(result.size()<start){
            return null;
        }

        if(result.size()<end){
            end=result.size();
        }

        result=result.subList(start,end);
        return result;
    }

    public void setGoodsFav(List<Favorite> favoriteList, GoodsView goodsView){
        if(favoriteList==null || favoriteList.size()<=0) return;
        if(favoriteList.stream().anyMatch(g->g.getGoods_id()==goodsView.getGoods_id())){
            goodsView.setIsFav(true);
        }
    }

}
